package org.linlinjava.litemall.brand.web;

import com.github.pagehelper.PageInfo;
import org.linlinjava.litemall.brand.annotation.LoginUser;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.DisputeConstant;
import org.linlinjava.litemall.db.util.OrderConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("service/order")
public class ServiceOrderController {
    @Autowired
    LitemallOrderService orderService;
    @Autowired
    LitemallServiceService serviceService;
    @Autowired
    LitemallOrderGoodsService orderGoodsService;
    @Autowired
    LitemallOrderReportService reportService;
    @Autowired
    LitemallCustomerService customerService;
    @Autowired
    LitemallBrandInfoService brandInfoService;
    @Autowired
    LitemallDisputeService disputeService;


    @PostMapping("list")
    public Object list(@RequestBody String msg, @LoginUser Integer userId) {
        Integer belong = serviceService.getBelong(userId);
        if (belong == null || belong > 0) {
            return ResponseUtil.unauthz();
        }
        Integer page = JacksonUtil.parseInteger(msg, "page");
        Integer pageSize = JacksonUtil.parseInteger(msg, "pageSize");
        if (page == null || pageSize == null) {
            return ResponseUtil.badArgument();
        }
        if (page < 0 || pageSize < 0) {
            return ResponseUtil.badArgumentValue();
        }
        String condition = JacksonUtil.parseString(msg, "condition");
        String sort = JacksonUtil.parseString(msg, "sort");
        PageInfo<LitemallOrder> orderPageInfo = orderService.listAdmin(condition, page, pageSize, sort);
        List<LitemallOrder> list = orderPageInfo.getList();
        for (LitemallOrder order : list) {
            Map<String, Object> map = new LinkedHashMap<>();
            List<LitemallOrderGoods> goodsList = orderGoodsService.queryByOid(order.getId());
//            LocalDateTime confirmTime = order.getConfirmTime();
//            LocalDateTime payCreateTime = order.getPayCreateTime();
//
//            if (confirmTime != null) {
//                order.setConfirmTime(confirmTime.plusHours(24));
//            }
//            if (payCreateTime != null) {
//                order.setPayCreateTime(payCreateTime.plusHours(2));
//            }
            order.setStatusName();
            map.put("commodityNum", goodsList.size());
            map.put("commodity", goodsList);
            order.setDetailInfo(map);
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("list", orderPageInfo.getList());
        map.put("totalNum", orderPageInfo.getTotal());
        return ResponseUtil.ok(map);
    }

    @PostMapping("detail")
    public Object detail(@RequestBody String msg, @LoginUser Integer userId) {
        Integer belong = serviceService.getBelong(userId);
        if (belong == null || belong > 0) {
            return ResponseUtil.unauthz();
        }
        Integer id = JacksonUtil.parseInteger(msg, "id");
        if (id == null || id < 1) {
            return ResponseUtil.badArgument();
        }
        LitemallOrder order = orderService.detail(id);
        List<LitemallOrderGoods> goodsList = orderGoodsService.queryByOid(order.getId());
        List<LitemallOrderReport> reportList = reportService.queryByOid(order.getId());
        LitemallCustomer customer = customerService.getUser((long) (order.getUserId()));
        LitemallBrandInfo brand = brandInfoService.getInfoByBrandId(order.getBrandId());
        BigDecimal sum = new BigDecimal(0);
        for (LitemallOrderGoods goods : goodsList) {
            sum = sum.add(goods.getGoodsPriceOrigin());
        }
        BigDecimal actualPrice = order.getActualPrice();
        for (LitemallOrderGoods goods : goodsList) {
            BigDecimal actual = goods.getGoodsPriceOrigin().divide(sum, 2, BigDecimal.ROUND_HALF_UP).multiply(actualPrice);
            goods.setGoodsPriceActual(actual);
        }
        order.setStatusName();
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("commodityNum", goodsList.size());
        map.put("commodityOriginPrice", sum);
        map.put("reportNum", reportList.size());
        map.put("order", order);
        map.put("report", reportList);
        map.put("commodity", goodsList);
        map.put("customer", customer);
        map.put("brand", brand);
        return ResponseUtil.ok(map);
    }

    @PostMapping("receive")
    public Object receive(@RequestBody String msg, @LoginUser Integer userId) {
        Integer belong = serviceService.getBelong(userId);
        if (belong == null || belong > 0) {
            return ResponseUtil.unauthz();
        }
        Integer orderId = JacksonUtil.parseInteger(msg, "orderId");
        if (orderId == null || orderId < 1) {
            return ResponseUtil.badArgument();
        }
        LitemallOrder order = orderService.findById(orderId);
        if (order == null || !order.getOrderStatus().equals(OrderConstant.PAYING)) {
            return ResponseUtil.badArgumentValue();
        }
        order.setOrderStatus(OrderConstant.PAYED);
        orderService.updateWithOptimisticLocker(order);
        return ResponseUtil.ok();
    }

    @PostMapping("receiveMargin")
    public Object receiveMargin(@RequestBody String msg, @LoginUser Integer userId) {
        Integer belong = serviceService.getBelong(userId);
        if (belong == null || belong > 0) {
            return ResponseUtil.unauthz();
        }
        Integer disputeId = JacksonUtil.parseInteger(msg, "disputeId");
        if (disputeId == null || disputeId < 1) {
            return ResponseUtil.badArgument();
        }
        LitemallDisputeOrder order = disputeService.findOrderById(disputeId);
        if (order == null || !order.getState().equals(DisputeConstant.WAIT_PAYING)) {
            return ResponseUtil.badArgumentValue();
        }
        order.setState(DisputeConstant.RECHECKING);
        disputeService.updateWithOptimisticLocker(order);
        return ResponseUtil.ok();
    }
}
